CREATE TABLE holiday(
id serial,
holiday_date date,
description text)

DROP FUNCTION get_public_date(date);

CREATE FUNCTION get_public_date(date) RETURNS date AS $$
DECLARE
data ALIAS FOR $1;
result boolean;
holiday_result boolean;
weekend_result integer;
count_holiday integer;
dat date;

BEGIN
dat:=$1;
result := FALSE;
holiday_result := FALSE;


LOOP

SELECT COUNT(*) INTO count_holiday FROM holiday WHERE holiday_date = dat;
IF(count_holiday)>0 THEN
holiday_result := TRUE;
END IF;


IF((SELECT EXTRACT(DOW FROM dat) = 0) OR (SELECT EXTRACT(DOW FROM dat)=6 )OR count_holiday>0) THEN 
dat:=dat-interval '1 day';
ELSE
result:=true;
END IF;

EXIT WHEN result =true;
END LOOP;

RETURN dat;

END;
$$ LANGUAGE 'plpgsql';
